package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.dto.ExamAnswerDTO;
import com.eduplatform.entity.ExamAnswer;
import com.eduplatform.entity.User;
import com.eduplatform.mapper.ExamAnswerMapper;
import com.eduplatform.mapper.UserMapper;
import com.eduplatform.service.ExamAnswerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 考试答题记录服务实现类
 */
@Service
public class ExamAnswerServiceImpl extends ServiceImpl<ExamAnswerMapper, ExamAnswer> implements ExamAnswerService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<ExamAnswerDTO> pageExamAnswers(Integer page, Integer size, Long examPaperId, Long questionId,
            Integer status) {
        Page<ExamAnswer> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<ExamAnswer> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (examPaperId != null) {
            wrapper.eq(ExamAnswer::getExamPaperId, examPaperId);
        }

        if (questionId != null) {
            wrapper.eq(ExamAnswer::getQuestionId, questionId);
        }

        if (status != null) {
            wrapper.eq(ExamAnswer::getStatus, status);
        }

        // 按创建时间降序排序
        wrapper.orderByDesc(ExamAnswer::getCreateTime);

        // 分页查询
        Page<ExamAnswer> result = this.page(pageParam, wrapper);

        // 转换为DTO
        List<ExamAnswerDTO> examAnswerDTOs = result.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        // 构建返回结果
        Page<ExamAnswerDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(result, dtoPage, "records");
        dtoPage.setRecords(examAnswerDTOs);

        return dtoPage;
    }

    @Override
    public ExamAnswerDTO getExamAnswerDetail(Long id) {
        ExamAnswer examAnswer = this.getById(id);
        if (examAnswer == null) {
            return null;
        }
        return convertToDTO(examAnswer);
    }

    @Override
    public List<ExamAnswerDTO> getExamAnswersByPaperId(Long examPaperId) {
        LambdaQueryWrapper<ExamAnswer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamAnswer::getExamPaperId, examPaperId);
        wrapper.orderByAsc(ExamAnswer::getId);

        List<ExamAnswer> examAnswers = this.list(wrapper);
        return examAnswers.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSaveExamAnswers(List<ExamAnswer> examAnswers) {
        if (examAnswers == null || examAnswers.isEmpty()) {
            return false;
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        for (ExamAnswer answer : examAnswers) {
            answer.setCreateTime(now);
            answer.setUpdateTime(now);
        }

        return this.saveBatch(examAnswers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean gradeExamAnswer(Long id, Integer score, String comment, Long graderId) {
        if (id == null || score == null || graderId == null) {
            return false;
        }

        ExamAnswer examAnswer = this.getById(id);
        if (examAnswer == null) {
            return false;
        }

        // 设置批改信息
        examAnswer.setScore(score);
        examAnswer.setComment(comment);
        examAnswer.setGraderId(graderId);
        examAnswer.setGradeTime(LocalDateTime.now());
        examAnswer.setStatus(1); // 已批改
        examAnswer.setUpdateTime(LocalDateTime.now());

        return this.updateById(examAnswer);
    }

    /**
     * 将ExamAnswer实体转换为DTO
     */
    private ExamAnswerDTO convertToDTO(ExamAnswer examAnswer) {
        ExamAnswerDTO dto = new ExamAnswerDTO();
        BeanUtils.copyProperties(examAnswer, dto);

        // 获取批改人信息
        if (examAnswer.getGraderId() != null && examAnswer.getGraderId() > 0) {
            User grader = userMapper.selectById(examAnswer.getGraderId());
            if (grader != null) {
                dto.setGraderName(grader.getNickname());
            }
        }

        return dto;
    }
}